import calendar
from datetime import datetime, timedelta

from django.utils.timezone import now, localdate


def time_to_datetime(raw_time, is_nextday):
    """
    将“时间”类型转成“日期时间”类型
    返回时间为naive的datetime类型
    """
    # is_nextday:是否跨天
    str_time = str(localdate(now())) + ' ' + str(raw_time)
    real_time = datetime.strptime(str_time, '%Y-%m-%d %H:%M:%S')
    if is_nextday:
        return real_time + timedelta(days=1)
    else:
        return real_time


def datetime_add_hour(current_time, hour):
    """
    时间推后指定小时
    """
    return current_time + timedelta(hours=hour)


def get_current_month_start_and_end(date):
        """
        年份 date格式: 2017-09-08
        :param date:
        :return: 本月第一天日期和本月最后一天日期
        """
        if date.count('-') != 2:
            raise ValueError('- is error')
        year, month = str(date).split('-')[0], str(date).split('-')[1]
        end = calendar.monthrange(int(year), int(month))[1]
        start_date = '%s-%s-01 00:00:00+08:00' % (year, month)
        end_date = '%s-%s-%s 23:59:59+08:00' % (year, month, end)
        return start_date, end_date


